package ink.tiptop.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author ink.tiptop.zjf
 * @Title: publish
 * @Package ink.tiptop.common.config
 * @Description: swagger配置
 * @date 2020-08-05 16:42
 *
 * @Api 类/接口	描述类/接口主要用途
 * @ApiOperation 方法    描述方法的用途
 * @ApiImplicitParam 方法    用于描述接口的非对象参数
 * @ApiImplicitParams 方法    用于描述接口的非对象参数集
 * @ApiIgnore 类/方法/参数	Swagger 文档不会显示拥有该注解的接口
 * @ApiModel 参数实体类    可设置接口相关实体的描述
 * ApiModelProperty	参数实体类属性	可设置实体属性的相关描述
 *
 *
 * @Configuration
 * @EnableSwagger2
 * @ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
 * @ConditionalOnProperty(prefix = "swagger", value = "enable", matchIfMissing = true)
 * @EnableConfigurationProperties(SwaggerProperties.class)
 */
@Configuration
@EnableSwagger2
@ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
@ConditionalOnProperty(prefix = "swagger", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(SwaggerProperties.class)
public class Swagger2Configuration {

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties() {
        return new SwaggerProperties();
    }

    @Bean
    public Docket createRestApi() {
        SwaggerProperties properties = swaggerProperties();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(properties))
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(SwaggerProperties properties) {
        SwaggerProperties.Contact contact = properties.getContact();
        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .version(properties.getVersion())
                .contact(new Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
                .build();
    }
}
